package com.xym.sso.service;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xym.common.util.MD5Utils;
import com.xym.sso.mapper.UserMapper;
import com.xym.sso.pojo.User;

@Service
public class UserService {

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private RedisService redisService;
	
	private ObjectMapper mapper = new ObjectMapper();
	


	/**
	 * 验证
	 * @param param
	 * @param type
	 * @return
	 */
	public Boolean checkData(String param, Integer type) {
		User user = new User();
		switch (type) {
		case 1:
			user.setUsername(param);
			break;
		case 2:
			user.setPhone(param);
			break;
		case 3:
			user.setEmail(param);
			break;

		default:
			return null;
		}
		
		int i = userMapper.selectCount(user);
		if(i==0){
			return true;
		}
		return false;
	}

	/**
	 * 注册
	 * @param user
	 * @return
	 */
	public Boolean registerData(User user) {
		user.setPassword(MD5Utils.str2MD5(user.getPassword()));
		int i = this.userMapper.insertUser(user);
		return i==1;
	}

	/**
	 * 登录
	 * @param user
	 * @return
	 * @throws Exception 
	 */
	public String login(String username, String password) throws Exception {
		   User user = new User();
		   user.setUsername(username);
		 User user2 = this.userMapper.selectOne(user);
		 if(user2==null){
			 return null;
		 }
		 if(!StringUtils.equals(user2.getPassword(), MD5Utils.str2MD5(password))){
			 return null;
		 }
		//登录成功加密
		 String token = MD5Utils.str2MD5(username+System.currentTimeMillis());
		 //信息放入redis
		 redisService.set("Token_"+token, mapper.writeValueAsString(user2), 1800);
		 
		return token;
	}

	/**
	 * 查询登录信息
	 * @param token
	 * @return
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 */
	public User queryUserByToken(String token) throws JsonParseException, JsonMappingException, IOException {
		try {
			String json = redisService.get("Token_"+token);
			if(StringUtils.isEmpty(json)){
				return null;
			}
			//刷新存活时间
			this.redisService.expire("Token_"+token, 1800);
			
			User user = mapper.readValue(json,User.class);
			return user;
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return null;
	}

	
	
}
